package com.demo.coretech.proxys;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Random;

/**
 * @Authors：gaoyang
 * @CreateTime：2021/11/27 14:30
 * @Description：todo
 */
public class ProxyTest {

    public static void main(String[] args) {
        Object[] elements = new Object[1000];
        for (int i=0;i<elements.length;i++){
            Integer val = i+1;
            InvocationHandler handler = new TraceHandler(val);
            Object proxy = Proxy.newProxyInstance(null,new Class[]{Comparable.class},handler);
            elements[i] = proxy;
        }
        Integer key = new Random().nextInt(elements.length)+1;
        int reuslt = Arrays.binarySearch(elements,key);
        if (reuslt>0){
            System.out.println(elements[reuslt]);
        }
    }

}
class TraceHandler implements InvocationHandler{

    private Object target;

    public TraceHandler(Object object) {
        this.target = object;
    }

    @Override
    public Object invoke(Object o, Method method, Object[] args) throws Throwable {
        System.out.print(target);
        System.out.print("."+ method.getName()+"(");
        if (args!=null){
            for (int i=0;i< args.length;i++){
                System.out.print(args[i]);
                if (i< args.length-1){
                    System.out.print(", ");
                }
            }
        }
        System.out.println(")");
        return method.invoke(target,args);
    }
}